# 选课系统
import os
import sys
import pickle


class SaveData(object):
    '''
    保存或加载数据
    '''

    @staticmethod
    def save_data(obj, path):
        '''
        保存数据
        '''
        with open(path, 'wb') as f:
            pickle.dump(obj, f)
        return True

    @staticmethod
    def load_data(path):
        '''
        加载数据
        '''
        with open(path, 'rb') as f:
            data = pickle.load(f)
        return data


class School(SaveData):
    '''
    定义学校类
    '''

    def __init__(self, name, addr):
        self.name = name
        self.addr = addr
        self.grades = []
        self.courses = []
        self.teachers = []
        self.students = []

    def add_grade(self, grade_obj):
        self.grades.append(grade_obj)

    def add_course(self, course_obj):
        self.courses.append(course_obj)

    def hire(self, teacher_obj):
        self.teachers.append(teacher_obj)

    def register(self, stu_obj):
        self.students.append(stu_obj)

    def info(self):
        print(' School info '.center(50, '-'))
        print('School name: %s' % self.name)
        print('School address: %s' % self.addr)
        print('-'*50)
        if self.grades:
            for grade in self.grades:
                grade.info()
        else:
            print('Not found grade information')

        if self.courses:
            for course in self.courses:
                course.info()
        else:
            print('Not found course information')

        if self.teachers:
            for teacher in self.teachers:
                teacher.info()
        else:
            print('Not fount teachers information')
        if self.students:
            for student in self.students:
                student.info()
        else:
            print('Not fount stutends information')


class Course(SaveData):
    '''
    定义课程类
    '''

    def __init__(self, name, term, price):
        self.name = name
        self.term = term
        self.price = price

    def info(self):
        print(' Course info '.center(50, '-'))
        print('Course name: %s ' % self.name)
        print('Course term: %s ' % self.term)
        print('Course price: %s' % self.price)
        print('-'*50)


class Grade(SaveData):
    '''
    定义班级类
    '''

    def __init__(self, name):
        self.name = name
        self.courses = []
        self.students = []

    def add_course(self, course_obj):
        self.courses.append(course_obj)
    def add_student(self, stu_obj):
        self.students.append(stu_obj)

    def info(self):
        print(' Grade info '.center(50, '-'))
        print('Grade name: %s' % self.name)
        for course in self.courses:
            course.info()
        print('-'*50)


class Teacher(SaveData):
    '''
    定义讲师类
    '''

    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

    def info(self):
        print(' Teacher info '.center(50, '-'))
        print('Teacher name: %s' % self.name)
        print('Teacher age: %s' % self.age)
        print('Teacher salary: %s' % self.salary)
        print('-'*50)


class Student(SaveData):
    '''
    定义学员类
    '''

    def __init__(self, name, age, stu_id):
        self.name = name
        self.age = age
        self.stu_id = stu_id

    def info(self):
        print(' Student info '.center(50, '-'))
        print('Student Id: %s' % self.stu_id)
        print('Student name: %s' % self.name)
        print('Student age: %s' % self.age)
        print('-'*50)


def admin_view():
    '''
    管理入口
    '''
    print(' admin view '.center(50, '-'))
    schools = [{'name': 'txketang', 'addr': 'beijing'},
               {'name': '163ketang', 'addr': 'shanghai'}]
    schools_num = len(schools)
    for i in range(schools_num):
        print('[%s] %s' % (i, schools[i]['name']))

    print('[q] exit system')
    choice = input('enter your choice: ')
    if choice.isdigit():
        choice = int(choice)
        school = schools[choice]
        if os.path.isfile(school['name']):
            school = School.load_data(school['name'])
        else:
            school = School(school['name'], school['addr'])
            school.save_data(school, school.name)

        print(' Welcome to %s '.center(50, '-') % school.name)
        while True:
            print('-'*50)
            print('[0] school information')
            print('[1] hire teacher')
            print('[2] add new grade')
            print('[3] add new course')
            print('[4] fire teacher')
            print('[5] delete grade')
            print('[6] delete course')
            print('[b] go back')
            print('[q] exit system')
            choice = input('Enter your choice: ')
            if choice == 'q':
                print('exit...')
                exit()
            elif choice == 'b':
                break
            elif choice == '0':
                school.info()
            elif choice == '1':
                print('will hire a new teacher')
                t_name = input('teacher name: ')
                t_age = input('teacher age: ')
                t_salary = input('teacher salary: ')
                if all((t_name, t_age, t_salary)):
                    teacher_obj = Teacher(t_name, t_age, t_salary)
                    teacher_obj.info()
                    school.hire(teacher_obj)
                    if school.save_data(school, school.name):
                        print('OK: hire a new teacher %s success' % t_name)
                    else:
                        print('Error: hire a new teacher %s failed' % t_name)
                else:
                    print('Error: invalid input')
            elif choice == '2':
                print('will add a new grade')
                g_name = input('grade name: ')
                if g_name:
                    grade_obj = Grade(g_name)
                    school.add_grade(grade_obj)
                    if school.save_data(school, school.name):
                        print('OK: add a new grade %s success' % g_name)
                    else:
                        print('Error: add a new grade %s failed' % g_name)
                else:
                    print('Error: invalid input')
            elif choice == '3':
                print('will add a new course')
                c_name = input('course name: ')
                c_term = input('course term: ')
                c_price = input('course price: ')
                g_name = input('grade name: ')
                if all((c_name, c_term, c_price, g_name)):
                    course_obj = Course(c_name, c_term, c_price)
                    for grade in school.grades:
                        if grade.name == g_name:
                            grade.add_course(course_obj)
                            break
                    else:
                        print(
                            'Error: not found the grade %s, add a new course %s failed' % (g_name, c_name))
                        continue
                    school.add_course(course_obj)
                    if school.save_data(school, school.name):
                        print('OK: add a new course %s success' % c_name)
                    else:
                        print('Error: add a new course %s failed' % g_name)
                else:
                    print('Error: invalid input')
            elif choice == '4':
                print('will fire a teacher')
                t_name = input('teacher name: ')
                if t_name:
                    for teacher in school.teachers:
                        if teacher.name == t_name:
                            school.teachers.remove(teacher)
                            if school.save_data(school, school.name):
                                print('OK: fired teacher %s' % t_name)
                                break
                            else:
                                print('Error: fire teacher %s failed' % t_name)
                else:
                    print('Error: invalid input')
            elif choice == '5':
                print('will delete a grade')
                g_name = input('grade name: ')
                if g_name:
                    for grade in school.grades:
                        if grade.name == g_name:
                            school.grades.remove(grade)
                            if school.save_data(school, school.name):
                                print('OK: grade %s deleted' % g_name)
                                break
                            else:
                                print('Error: grade %s deleted failed' %
                                      g_name)
                    else:
                        print('Not found the grade %s' % g_name)
                else:
                    print('Error: invalid input')
            elif choice == '6':
                print('will delete a course')
                c_name = input('course name: ')
                if c_name:
                    for course in school.courses:
                        if course.name == c_name:
                            school.courses.remove(course)
                            if school.save_data(school, school.name):
                                print('OK: course %s deleted' % c_name)
                                break
                            else:
                                print('Error: course %s deleted failed' %
                                      c_name)
                    else:
                        print('Not found the course %s' % c_name)
                else:
                    print('Error: invalid input')
    elif choice == 'q':
        print('exit...')
        exit()


def teacher_view():
    '''
    讲师入口
    '''
    print(' teacher view '.center(50, '-'))

def student_view():
    '''
    学员入口
    '''
    print(' student view '.center(50, '-'))
    schools = ['txketang', '163ketang']
    for school in schools:
        print('[%s] %s' % (schools.index(school), school))
    print('[q] exit')

    choice = input('enter your choice: ')
    if choice.isdigit():
        choice = int(choice)
        school = schools[choice]
        if os.path.isfile('txketang'):
            school = School.load_data(school)
        else:
            print('Error: not found the school %s ' % school)
            return
        print(' Welcome %s schoole '.center(50, '-') % school.name)
        school.info()
        while True:
            print('[0] school information')
            print('[1] register')
            print('[b] go back')
            print('[q] exit')
            choice = input('enter your choice: ')
            if choice == 'q':
                print('exit...')
                exit()
            elif choice == 'b':
                break
            elif choice == '0':
                school.info()
            elif choice == '1':
                s_name = input('student name: ')
                s_age = input('student age: ')
                if school.students:
                    stu_id = school.students[-1].stu_id + 1
                else:
                    stu_id = 1
                g_name = input('grade name: ')
                if all((s_name, s_age, g_name)):
                    for grade in school.grades:
                        if grade.name == g_name:
                            stu_obj = Student(s_name, s_age, stu_id)
                            grade.students.append(stu_obj)
                            school.students.append(stu_obj)
                            if school.save_data(school, school.name):
                                print('OK: student %s register success' % s_name)
                                break
                            else:
                                print('OK: student %s register failed' % s_name)
                    else:
                        print('Error: not found the grade %s ' % g_name)
                else:
                    print('Error: invalid input')


    elif choice == 'q':
        print('exit ...')
        exit()


def main():
    '''
    系统入口
    '''
    while True:
        print('[1] Admin Entrance')
        print('[2] Teacher Entrance')
        print('[3] Student Entrance')
        print('[q] Exit System')
        choice = input('Enter your chocie: ')
        if choice == '1':
            while True:
                admin_view()
        elif choice == '2':
            while True:
                teacher_view()
        elif choice == '3':
            while True:
                student_view()
        elif choice == 'q':
            print('exit ...')
            exit()


if __name__ == '__main__':
    main()
